package com.myway.ibe.command;

import com.myway.ibe.domain.IBEPassenger;
import com.myway.ibe.domain.IBEPnr;
import com.myway.ibe.domain.IBESegment;
import com.myway.ibe.enums.PassengerType;
import com.myway.ibe.exception.IBEException;
import com.travelsky.ibe.client.pnr.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

/**
 * Created by Administrator on 2018/1/15.
 * 散客PNR预定
 */
@Slf4j
public class ReservePNRCommand extends BaseIBECommand {
    @Override
    public void execute(Map<String, Object> params) {
            DTOIBELogs ibeETDZLog = new DTOIBELogs();
            List<DTOSegment> segmentList = (List<DTOSegment>) params
                    .get("segmentList");
            List<DTOPassenger> passengerList = (List<DTOPassenger>) params
                    .get("passengerList");
            DTOOrder dtoOrder = (DTOOrder) params.get("order");
            DTOFltChange fltChange = (DTOFltChange) params.get("fltChange");
            String contactNo = (String) params.get("contactNo");
            AirlineConfigs ac = (AirlineConfigs) SpringBeanUtil.lookup(airline
                    + "Config");
            // 如果是西部联名卡产品需要添加 OSI PN CMBPCK.....add by zhengxing
            String osiInfo = null;
            SellSeat ss = null;
            QDateTime qtime = new QDateTime();
            // 航段类型 单程OW、来回程RT
            String tripType = "OW";
            String cabinCode = "";
            // 承运人
            String airlineCode = "";
            // 销售类型 B2B/C
            String userType = "";
            //积分信息 在FP中增加
            String JFinfo="";
            for (DTOSegment seg : segmentList) {
                airlineCode = seg.getAirlineCode().toUpperCase();
                break;
            }
            boolean yxtxUser = false;
            if (dtoOrder.getUser() != null) {
                if (dtoOrder.getUser().getUserType() == UserConstants.AGENT) {
                    userType = "B2B";
                }
                if (dtoOrder.getUser().getUserType() == UserConstants.USER) {
                    userType = "B2C";
                }

                if ("Y".equals(dtoOrder.getCardRemark())) {
                    yxtxUser = true;
                }

            }
            try {
                ss = new SellSeat();
                // 设置IBE参数
                configIBEClient(ss, airline, ibeETDZLog);
                log.debug("start create PNR.....");

                Date dateLimt = null;
                // Add AirSegment ...
                List<DTOSegment> continualSegments = PNRUtils.generatorContinual4Multi(segmentList);

                // 判断旅客类型是否是儿童，如果是，舱位号变为Y
			/* 按如下判断逻辑，第一航段的判断结果会影响所有航段
			 * String childCabinClass = "";
			boolean childPasseger = false;
			if (passengerList.size() > 0) {
				DTOPassenger pax = passengerList.get(0);
				List<DTOPaxSegment> paxSegList = pax.getPassengerSegmentList();
				if (paxSegList != null && paxSegList.size() > 0) {
					childPasseger = pax.getPassengerType() == PassengerType.CHILD;
					if (childPasseger) {
						List<DTOPaxSegment> paxList = pax
								.getPassengerSegmentList();
						if (paxList != null && paxList.size() > 0) {
							DTOPaxSegment dtoPaxSegment = paxList.get(0);
							if (("YBHKLMQXUE".indexOf(dtoPaxSegment
									.getCabinClass()) >= 0  ||
									(dtoPaxSegment.getFlightNo().startsWith("JD") && "I".indexOf(dtoPaxSegment.getCabinClass()) >=0)
									|| ("PN".equals(airline) && "NI".indexOf(dtoPaxSegment.getCabinClass()) >= 0))
									&& (dtoPaxSegment.getBaseFare() > 0.000001)
									&& (int) (dtoPaxSegment.getMarketFare()
											/ dtoPaxSegment.getBaseFare() * 100) >= 50) {
								// paxSeg.setCabinClass("Y");
								childCabinClass = "Y";
							}
						}
					}
				}
			}*/

                boolean childPasseger = passengerList.size() > 0 &&
                        passengerList.get(0).getPassengerType() == PassengerType.CHILD;
                int i = 0;
                for (DTOSegment segment : continualSegments) {
                    i ++;
                    // IBE Inventory then add to ss
                    if (segment.getInventory() == Inventory.IBE) {
                        log.debug("add segment....." + segment.getFlightNo());
                        BookAirSeg airseg = null;
                        if (ACTION_CODE_SA.equals(segment.getCabinState())) {
                            //股份优惠机票不订座第1段使用信息航段
                            if(dtoOrder.getAirlineCode() != null &&
                                    dtoOrder.getAirlineCode().equals("HU") &&
                                    dtoOrder.getSource() != null &&
                                    dtoOrder.getSource().equals("HD") &&
                                    segment.getDepTime() != null) {
                                if(i == 1) {
                                    airseg = new BookAirSeg(segment.getFlightNo(),
                                            segment.getCabinClass().charAt(0),
                                            segment.getDepCode(), segment.getArrCode(),
                                            ACTION_CODE_SA, 1, segment.getDepTime());
                                } else if(segment.getFlightNo() != null && !segment.getFlightNo().trim().equals("")) {
                                    //预定Open航段
                                    airseg = new BookAirSeg(segment.getFlightNo(), segment.getCabinClass().charAt(0), segment.getDepCode(), segment.getArrCode());
                                } else {
                                    //预定信息航段
                                    airseg = new BookAirSeg(segment.getDepCode(), segment.getArrCode());
                                    airseg.setActionCode(ACTION_CODE_SA);
                                }
                            } else {
                                airseg = new BookAirSeg(segment.getDepCode(),
                                        segment.getArrCode());
                                airseg.setActionCode(ACTION_CODE_SA);
                            }
                        } else {
                            String childCabinClass = "";
                            //如果是儿童，需要看舱位是否需要变成Y
                            if(childPasseger && passengerList.size() > 0) {
                                for(DTOPassenger childPassenger : passengerList) {
                                    if(childPassenger.getPassengerSegmentList() != null) {
                                        for(DTOPaxSegment childPax : childPassenger.getPassengerSegmentList()) {
                                            if(childPax.getDepCode().equals(segment.getDepCode()) &&
                                                    childPax.getArrCode().equals(segment.getArrCode())) {
                                                childCabinClass = ChildCanbinConverter.
                                                        getInstance(airline).convertChildCabin(dtoOrder, childPax);
                                                break;
                                            }
                                        }
                                        break;
                                    }
                                }
                            }
                            if (childPasseger && !TextUtil.isEmpty(childCabinClass)) {
                                airseg = new BookAirSeg(segment.getFlightNo(),
                                        childCabinClass.charAt(0),
                                        segment.getDepCode(), segment.getArrCode(),
                                        ACTION_CODE_HK, 1, segment.getDepTime());
                            } else {
                                airseg = new BookAirSeg(segment.getFlightNo(),
                                        segment.getCabinClass().charAt(0),
                                        segment.getDepCode(), segment.getArrCode(),
                                        ACTION_CODE_HK, 1, segment.getDepTime());
                            }
                        }
                        ss.addAirSeg(airseg);
                        if (dtoOrder.getTimeLimit() != null) {
                            dateLimt = dtoOrder.getTimeLimit();
                        } else if (segment.getDepTime() != null
                                && (dateLimt == null || segment.getDepTime()
                                .before(dateLimt))) {
                            dateLimt = segment.getDepTime();
                        }
                    }
                    cabinCode = segment.getCabinClass();

                }

                int adultIndex = 0;
                int infantIndex = 0;
                PNRFC fc = new PNRFC();
                PNRFN fn = new PNRFN(airline);

                PNRFC infantFC = null;
                PNRFN infantFN = null;

                if(null!=dtoOrder.getUser()){
                    fc.setUsertype(dtoOrder.getUser().getUserType());
                }


                // For adult and child.....
                int bxl_count=0;
                for (DTOPassenger pax : passengerList) {
                    bxl_count++;
                    log.debug("add pax.....");
                    // Add Pax and child ....
                    // Add Pax.....
                    ss.addPassenger(new BookPassenger( pax.getName(),
                            pax.getPassengerType() == PassengerType.ADULT ? PASSENGER_ADULT : PASSENGER_CHILD, 0));
                    // Add Pax ID No....
                    ss.addSSR_FOID(airline, ID_TYPE_NI, pax.getCertificateNo(), pax.getName());

                    //增加SSR CHLD项
                    if(childPasseger){
                        BookSSR bookssr=new BookSSR("CHLD", airlineCode, "hk", 1, "", "", ' ', "", qtime.dateToString(pax.getBirthday(), "ddmmmyy"), pax.getName());
                        ss.addSSR(bookssr);
                    }

                    if(yxtxUser){
                        ss.addSSR(new BookSSR("CKIN","GS HK1 YFCD/P"+bxl_count));
                    }

                    //天航头等悠享(P舱) SSR项
                    if(airlineCode!=null && cabinCode!=null && airlineCode.equals("GS") && cabinCode.equals("P")){
                        ss.addSSR(new BookSSR("CKIN","GS GSPC HK1/P"+bxl_count));
                    }

//				TSZK
                    String code = pax.getPassengerSegmentList().get(0).getProductApplied().getCode();
                    if(airlineCode!=null && cabinCode!=null && airlineCode.equals("GS") && "TSZK".equals(code)){
                        ss.addSSR(new BookSSR("CKIN","GS TSZK HK1/P"+bxl_count));
                    }


                    //首航超值头等舱产品 SSR项
                    if(airlineCode != null&&cabinCode!=null&&airlineCode.equals("JD")&&cabinCode.equals("A")){
                        ss.addSSR(new BookSSR("CKIN","JD CZTD HK1/P"+bxl_count));
                    }

                    // 天航惠通天下2(N舱) SSR项
                    if(airlineCode != null&&cabinCode!=null&&airlineCode.equals("GS")&&cabinCode.equals("N")){
                        ss.addSSR(new BookSSR("CKIN","GS HTTX HK1/Pn"));
                    }

                    // 天航微特权(R舱) SSR项
                    if(airlineCode != null&&cabinCode!=null&&airlineCode.equals("GS")&&cabinCode.equals("R")){
                        ss.addSSR(new BookSSR("CKIN","GS WXTQ HK1/P"+bxl_count));
                    }

                    // 百姓乐产品(I舱) 增加PNR备注 add jxin-tang
//				if(airlineCode != null&&cabinCode!=null&&airlineCode.equals("GS")&&cabinCode.equals("I")){
//					ss.addSSR(new BookSSR("CKIN","GS BXL HK1/P"+bxl_count));
//				}

                    //多等级  联系人用OSI GS CTCT 手机号，乘机人用OSI GS CTCM 手机号/Pn
                    if(airlineCode != null&&airlineCode.equals("GS")){
                        if(null != pax.getMobilePhone() && !"".equals(pax.getMobilePhone().trim())){
                            ss.addOSI("GS", "GS CTCM"+pax.getMobilePhone()+"/P"+bxl_count);
//						ss.addOSI(new BookOSI("GS", "CTCM"+pax.getMobilePhone()+"/P"+bxl_count));
                        }
                    }
                    //PGSLUCKYAIR-658 "PNR强制输入手机号"补充功能增加 --begin
                    if(airlineCode != null&&airlineCode.equals("8L")){
                        //ss.addOSI("8L", "OSI 8L CTCT"+dtoOrder.getContactMobile());
                        //乘机人手机号码为空时，add 订单联系人 手机号，反之 add 乘机人手机号
                        if(null != pax.getMobilePhone() && !"".equals(pax.getMobilePhone().trim())){
                            ss.addOSI("8L", "OSI 8L CTCM"+pax.getMobilePhone()+"/P"+bxl_count);
                        }

                    }
                    //PGSLUCKYAIR-658 "PNR强制输入手机号"补充功能增加 --end
                    // Add FFP No....
                    if (ac != null && ac.isOpenFFP()) {
                        if (pax.getFrequentflyerno() != null && !pax.getFrequentflyerno().equals("")) {
                            // 西部航空
                            ss.addSSR_FQTV(airline, "HU" + pax.getFrequentflyerno(), pax.getName());
                        }
                    }
                    if (adultIndex == 0) {
                        fc.setSegments(pax.getPassengerSegmentList());
                        fc.setChild(pax.getPassengerType() == PassengerType.CHILD ? true : false);
                        fn.setSegments(pax.getPassengerSegmentList());
                        if (ac != null && ac.isOpenEI()) {
                            // 设置EI信息
                            List<DTOPaxSegment> list = pax.getPassengerSegmentList();
                            DTOPaxSegment dtoPaxSegment=null;
                            for (DTOPaxSegment dtoPaxSegment0 : list) {
                                if(dtoPaxSegment==null){
                                    dtoPaxSegment=dtoPaxSegment0;
                                }
                                if(dtoPaxSegment0.getSequence()>dtoPaxSegment.getSequence()){
                                    dtoPaxSegment=dtoPaxSegment0;
                                }
                            }
                            String isfltchange = "";
                            //FltChangeDaoImpl fltchange = new FltChangeDaoImpl();
                            //判断是否为升舱改期订单
                            //添加 给航空 西部、祥鹏、天津 三家航空公司
                            //取消祥鹏、天津升舱改期
                            if(dtoOrder.getFltChange() !=null  ){
                                if (dtoOrder.getFltChange().size() != 0 && "8L".indexOf(airlineCode) >= 0){
                                    isfltchange = "yes";
                                }

                                //如果是西部的改期升舱订单，设置出票时限为订票时间+30分钟
                                if(dtoOrder.getFltChange().size() != 0 && "PN".indexOf(airlineCode) >= 0){
                                    dateLimt=new Date(dtoOrder.getFltChange().get(dtoOrder.getFltChange().size()-1).getCreateTime().getTime() + 1800000L);
                                }
                            }
                            if((("8LJD").indexOf(airlineCode)) >= 0&&dtoPaxSegment.getCouponPrice().longValue()>0 ){
                                //使用优惠劵的
                                //add by st-zuo
                                PNRItemEIHelper.getInstance().addFirstEI(ss, airlineCode, tripType, list, cabinCode, 1,isfltchange,pax.getName());
                            }else if((("8L").indexOf(airlineCode)) >= 0&&dtoPaxSegment.getPointPrice()>0 ){
//								String jfinfo=" JF"+(segmentList.size()*dtoPaxSegment.getPointPrice());
                                String jfinfo=" JF"+(dtoPaxSegment.getPointPrice());
                                if(segmentList.size()>1){
                                    jfinfo+="*"+segmentList.size();
                                }
                                JFinfo=jfinfo;
                                PNRItemEIHelper.getInstance().addEI_JF(ss, airlineCode, tripType, dtoPaxSegment, cabinCode, 1,isfltchange,jfinfo);
                            }else{
                                PNRItemEIHelper.getInstance().addEI(ss, airlineCode, tripType, dtoPaxSegment, cabinCode, 1,isfltchange);
                            }


                        }
                    }
                    //祥鹏优惠劵还要加一个EI项
                    if (airlineCode != null&&(("8LJD").indexOf(airlineCode)) >= 0&&adultIndex == 1) {
                        if (ac != null && ac.isOpenEI()) {
                            // 设置EI信息
                            List<DTOPaxSegment> list = pax.getPassengerSegmentList();
                            for (DTOPaxSegment dtoPaxSegment : list) {
                                String isfltchange = "";
                                //FltChangeDaoImpl fltchange = new FltChangeDaoImpl();
                                //判断是否为升舱改期订单
                                //添加 给航空 西部、祥鹏、天津 三家航空公司
                                //取消祥鹏、天津升舱改期
                                if(dtoOrder.getFltChange() !=null  ){
                                    if (dtoOrder.getFltChange().size() != 0 && (("8L").indexOf(airlineCode)) >= 0){
                                        isfltchange = "yes";
                                    }
                                }
                                if((("8LJD").indexOf(airlineCode)) >= 0&&dtoPaxSegment.getCouponPrice().longValue()>0 ){
                                    //使用优惠劵的
                                    PNRItemEIHelper.getInstance().addOthersEI(ss, airlineCode, tripType, list, cabinCode, 1,isfltchange);
                                }
                                break;
                            }
                        }
                    }

                    //将索引放在外面
                    adultIndex++;

                    // Add accomany infant....
                    if (CollectionUtils.isNotEmpty(pax
                            .getAccompanyingPassengerList())) {
                        // Add Infant....
                        for (DTOPassenger infant : pax
                                .getAccompanyingPassengerList()) {
                            ss.addInfant(infant.getBirthday(), pax.getName(),
                                    infant.getName());
                            //祥鹏增加婴儿SSR项，若无此项，则带婴儿编码无法生成。
                            if(airlineCode != null && airlineCode.equals("8L")){
                                for (DTOSegment segment : continualSegments) {
                                    ss.addSSR_INFT(airlineCode,segment.getDepCode()+segment.getArrCode(), segment.getFlightNo().substring(2, 6),
                                            segment.getCabinClass(),qtime.dateToString(segment.getDepTime(), "ddmmmyy"),
                                            CnToSpellNew.getPinYin(infant.getName().toString().substring(0, 1))+"/"+CnToSpellNew.getPinYin(infant.getName().toString().substring(1)),
                                            qtime.dateToString(infant.getBirthday(), "ddmmmyy"), "", pax.getName());
                                }
                            }

                            if (infantIndex == 0) {
                                infantFC = new PNRFC();
                                infantFC.setInfant(true);

                                if(null!=dtoOrder.getUser()){
                                    infantFC.setUsertype(dtoOrder.getUser().getUserType());
                                }
                                infantFN = new PNRFN(airline);
                                infantFN.setInfant(true);
                                infantFC.setSegments(infant
                                        .getPassengerSegmentList());
                                infantFN.setSegments(infant
                                        .getPassengerSegmentList());
                            }
                            infantIndex++;
                        }
                    }
                }
                //股份优惠机票只添加FN项
                if(dtoOrder.getAirlineCode() != null &&
                        dtoOrder.getAirlineCode().trim().equals("HU") &&
                        dtoOrder.getSource() != null &&
                        dtoOrder.getSource().trim().equals("HD")) {
                    // Add FN
                    log.debug("add FN.....");
                    log.debug(fn.toString());
                    ss.addFN(fn.toString());
                    if (infantFN != null) {
                        log.debug(infantFN.toString());
                        ss.addFN(infantFN.toString());
                    }
                }
                //散客积分支付FN\FC项打印
                else if(StringUtils.hasText(dtoOrder.getFullPointPay())&&"B2C".equals(userType))
                {
                    // Add FC
                    log.debug("add FC.....");
                    log.debug(fc.toString4Point());
                    ss.addFC(fc.toString4Point());
                    if (infantFC != null) {
                        log.debug(infantFC.toString());
                        ss.addFC(infantFC.toString4Point());
                    }
                    // Add FN
                    log.debug("add FN.....");
                    log.debug(fn.toString4Point());
                    ss.addFN(fn.toString4Point());
                    if (infantFN != null) {
                        log.debug(infantFN.toString4Point());
                        ss.addFN(infantFN.toString4Point());
                    }

                }else
                {
                    // Add FC
                    log.debug("add FC.....");
                    log.debug(fc.toString());
                    ss.addFC(fc.toString());
                    if (infantFC != null) {
                        log.debug(infantFC.toString());
                        ss.addFC(infantFC.toString());
                    }
                    // Add FN
                    log.debug("add FN.....");
                    log.debug(fn.toString());
                    ss.addFN(fn.toString());
                    if (infantFN != null) {
                        log.debug(infantFN.toString());
                        ss.addFN(infantFN.toString());
                    }
                }
                // Add FP
                log.debug("add FP.....");
                ss.addFP("CASH,CNY"+createFPForInsurance(passengerList,airline));
                log.debug("add time limit.....");
                // Set limit time to cancel
                ss.setTimelimit(dateLimt);

                log.debug("add contact.....");
                // Use telelphone for contact

                if (ac != null && ac.isReplaceContactNo()) {
                    ss.addContact(new BookContact(ac.getContactNo()));
                } else {
                    if(airlineCode!=null && (airlineCode.equals("8L") || airlineCode.equals("PN")|| airlineCode.equals("GS"))){//PGSLUCKYAIR-661 PNR中电话号码的限制和验证
                        ss.addContact(new BookContact("NO"));
                    }else{
                        ss.addContact(new BookContact(contactNo));
                    }
                }

                PNRItemOSIHelper.getInstance().addOSI(ss, airlineCode, passengerList.get(0), contactNo);

                // commit PNR .....
                SSResult result = ss.commit1();
                log.info("PNR Created....");
                log.info(result.getPnrno());
                DTOPnr pnr = new DTOPnr();
                pnr.setPnrNo(result.getPnrno());
                // 使用此返回值。
                params.put("PNRNo", pnr.getPnrNo());

                //记录IBE操作日志
                sendLogToSave(ibeETDZLog,"RESERVEPNR,PNRNo:" + pnr.getPnrNo(),pnr);

                insertPnrNOTOPax(passengerList,pnr,result);

                boolean pnrFlag = checkAllSegmentHK(result,passengerList);

                boolean inftFlag = false;
                if(airlineCode != null && airlineCode.equals("8L")){
                    inftFlag = checkInftStatus(pnr.getPnrNo(),airlineCode,passengerList);
                }

                if (pnrFlag || inftFlag) {
                    // pnr 中存在非HK航段，清理该PNR，并且异常抛出，取消订单生成
//				PNRManage.getInstance(airline).cancelSegment(result.getPnrno(),SegmentMapper.getInstance().mapToEntities(continualSegments));
                    PNRManage.getInstance(airline).cancelPnr4OrderCreatError(result.getPnrno(), dtoOrder);
                    log.info(" Not expected pnr status , cancel pnr["+pnr.getPnrNo()+"], cancel order["+dtoOrder.getOrderNo()+"]...");
                    throw new Exception(" 订单生成失败，你选择的舱位价格可能已不存在，请重新提交订单...");
                }
            } catch (Exception e) {
                sendLogToSave(ibeETDZLog,"RESERVEPNR ERROR ,the Reason is :" + e.getMessage(),null);

                if(e.getMessage().indexOf("失信被执行人")>-1){
                    log.error("==SubmitOrder  exception==订单含有失信人，预定编码失败"+e.getMessage());
                    throw new RuntimeException("预定失败，您预定的旅客名单中含法院通告的失信人，请与法院联系");
                }else{
                    log.error(e.getMessage(), e);
                    throw new IBEException(e.getMessage());
                }
            }
        }

        /**
         * <pre>
         * 西部在PNR中FP:CASH,CNY项增加代码，以对接结算系统进行区分
         * 		其中，“A@20”表示航意险20元，“B@20”表示航延险20元
         * 目前以保险中的ProtocolID进行区分，如果后续其它航空公司
         * 也有相同需求，可以增加字段
         * </pre>
         * @Auther 郑兴(zhengxing)
         * @Date 2012-9-28
         * @param passengerList
         * @return
         */
        private String createFPForInsurance(List<DTOPassenger> passengerList,String airline) {
            if(!airline.equals("PN")) {
                return "";
            }
            StringBuffer fp = new StringBuffer("/");
            //航空意外险投保额
            int accidentAmount = 0;
            //航延险投保额
            int delayAmount = 0;
            //特价退票保障险投保额
            int refundAmount = 0;
            for(DTOPassenger passenger : passengerList) {
                for(DTOPaxSegment pax : passenger.getPassengerSegmentList()) {
                    for(DTOInsurance insurance : pax.getInsuranceList()) {
                        if(insurance.getProductCode().equals(InsuranceConstant.INSURANCE_UNEXPECTED_CODE)) {
                            accidentAmount += insurance.getAmount();
                        } else if(insurance.getProductCode().equals(InsuranceConstant.INSURANCE_DELAY_CODE)) {
                            delayAmount += insurance.getAmount();
                        } else if(insurance.getProductCode().equals(InsuranceConstant.INSURANCE_REFUND_CODE)) {
                            refundAmount += insurance.getAmount();
                        }
                    }
                }
                if(!CollectionUtils.isEmpty(passenger.getAccompanyingPassengerList())) {
                    for(DTOPassenger infat : passenger.getAccompanyingPassengerList()) {
                        for(DTOPaxSegment pax : infat.getPassengerSegmentList()) {
                            for(DTOInsurance insurance : pax.getInsuranceList()) {
                                if(insurance.getProductCode().equals(InsuranceConstant.INSURANCE_UNEXPECTED_CODE)) {
                                    accidentAmount += insurance.getAmount();
                                } else if(insurance.getProductCode().equals(InsuranceConstant.INSURANCE_DELAY_CODE)) {
                                    delayAmount += insurance.getAmount();
                                } else if(insurance.getProductCode().equals(InsuranceConstant.INSURANCE_REFUND_CODE)) {
                                    refundAmount += insurance.getAmount();
                                }
                            }
                        }
                    }
                }
            }
            if(accidentAmount != 0) {
                fp.append("A@").append(accidentAmount);
            }
            if(delayAmount != 0) {
                fp.append("B@").append(delayAmount);
            }
            if(refundAmount != 0) {
                fp.append("C@").append(refundAmount);
            }
            if(fp.indexOf("@") == -1) {
                fp = new StringBuffer();
            }
            return fp.toString();
        }

        /**
         * 异步保存IBE操作日志
         *
         * @param ibeLog
         * @param message
         * @param pnr
         * @auther 郑兴(zhengxing)
         * 2012-4-9
         */
        private void sendLogToSave(DTOIBELogs ibeLog,String message,DTOPnr pnr) {
            try {
                ibeLog.setCreateTime(new Date());
                ibeLog.setIbeMethod(IBEMethodType.RESERVEPNR);
                ibeLog.setContent(message);
                if(null != pnr) {
                    ibeLog.setPnrNo(pnr.getPnrNo());
                }

                IBELogArtifact fact = new IBELogArtifact(ibeLog.getAirlineCode(), ibeLog);
                producer.send(fact);
            } catch (Exception e) {
                log.error("save ibe log error",e);
            }
        }

        /**
         * 为旅客(DTOPassenger)添加PNR信息
         *
         * @param passengerList
         * @param pnr
         * @param result
         * @auther 郑兴(zhengxing)
         * 2012-4-9
         */
        private void insertPnrNOTOPax(List<DTOPassenger> passengerList,DTOPnr pnr,SSResult result) {
            // set pnr back to pax...
            for (DTOPassenger pas : passengerList) {
                pas.setPnrValue(pnr);

                if (CollectionUtils.isNotEmpty(pas.getAccompanyingPassengerList())) {
                    // Set PNR to accompanying passengers (infant)
                    for (DTOPassenger ap : pas.getAccompanyingPassengerList()) {
                        ap.setPnrValue(pnr);
                    }
                }
            }
        }

        /**
         * 检查所有航段状态是否为HK
         *
         * @param result
         * @param passengerList
         * @return
         * @auther 郑兴(zhengxing)
         * 2012-4-9
         */
        private boolean checkAllSegmentHK(SSResult result,List<DTOPassenger> passengerList) {
            boolean pnrFlag = false;
            for(DTOPassenger pax : passengerList) {
                for(DTOPaxSegment ps : pax.getPassengerSegmentList()) {
                    for (int i = 0; i < result.getSegmentsCount() && !pnrFlag; i++) {
                        SSSegment sg = result.getSegmentAt(i);
                        // check segment action code......
                        if (sg.getAirNo().equalsIgnoreCase(ps.getFlightNo())
                                && sg.getOrgCity().equalsIgnoreCase(ps.getDepCode())
                                && sg.getDesCity().equalsIgnoreCase(ps.getArrCode())) {

                            // 此处异常抛出，导致往返程编码存在虚耗情况，订单无法生成，但编码已预订,修改
                            if (ps.getStatus() == SegmentStatus.HK) {
                                if (!"HK".equalsIgnoreCase(sg.getActionCode())) {
                                    log.info(" pnr status is " + sg.getActionCode() + ", not HK");
                                    log.info(" cancel this pnr  " + result.getPnrno());
                                    pnrFlag = true;
                                }
                            }
                            break;
                        }
                    }
                }
            }
            return pnrFlag;
        }


        /**
         * 检查带婴儿PNR中婴儿的SSR INFT项状态是否为KK或HK，如果不是则预订失败，并取消编码。
         *
         * @param pnr
         * @param airlineCode
         * @return
         * @auther 王思远(sy-wang)
         * 2013-8-14
         */
        private boolean checkInftStatus(String pnrNo,String airlineCode,List<DTOPassenger> passengerList) {
            boolean inftFlag = false;
            for(DTOPassenger pax : passengerList) {
                if (CollectionUtils.isNotEmpty(pax.getAccompanyingPassengerList())) {
                    RT rt = new RT();
                    PNRManage.configIBEClient(rt, airlineCode);
                    RTResult rtResult =null;
                    boolean flag = false;
                    int i = 3;
                    while(!flag && i>0){
                        try {
                            rtResult = rt.retrieve(pnrNo);
                            if(rtResult != null){
                                flag = true;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        i = i-1;
                    }
                    for(int j=0;j<rtResult.getSSRsCount();j++){
                        String ssrType = rtResult.getSSRAt(j).getSSRType();
                        String actionCode = rtResult.getSSRAt(j).getActionCode();
                        if(ssrType.equals("INFT")){
                            if(!actionCode.equals("KK") && !actionCode.equals("HK")){
                                inftFlag = true;
                                log.info(" INFT status is " + actionCode + ", not HK or KK");
                                log.info(" cancel this INFT pnr  " + pnrNo);
                            }
                        }
                    }
                }
            }
            return inftFlag;

        }


        /**
         * 根据配置文件获取EI信息（用于明折明扣）
         *
         * @param type
         *            类型OW 单程、RT 来回程
         *
         *
         *
         * @param cabinCode
         *            舱位代码
         * @param selectDiscount
         *            选择舱位折扣（无匹配舱位值可设置为-1）
         *
         *
         *
         * @return
         */
        @SuppressWarnings("unchecked")
        public static String getEI(String type, String cabinCode,
        double selectDiscount, String airlineCode, String userType) {
            Map<String, String> eiMap = null;
            // 祥鹏航空的EI项区分B2B/C
            if (airlineCode.equals("HU")) {
                eiMap = (Map<String, String>) SpringBeanUtil.lookup("HUEIInfo");
                // if(userType.equals( "B2B" )){
                // eiMap = (Map<String,
                // String>)SpringBeanUtil.lookup("L8EIInfoB2B");
                // }else if(userType.equals( "B2C" )){
                // eiMap = (Map<String,
                // String>)SpringBeanUtil.lookup("L8EIInfoB2C");
                // }else{
                // eiMap = (Map<String,
                // String>)SpringBeanUtil.lookup("L8EIInfoB2C");
                // }
            } else if (airlineCode.equals("GS")) {
                eiMap = (Map<String, String>) SpringBeanUtil.lookup("GSEIInfo");
            } else if (airlineCode.equals("PN")) {
                eiMap = (Map<String, String>) SpringBeanUtil.lookup("PNEIInfo");
            } else {
                eiMap = (Map<String, String>) SpringBeanUtil.lookup("EIInfo");
            }

            String returnVal = "";

            for (Entry<String, String> entry : eiMap.entrySet()) {
                String key = entry.getKey();
                // 将key变成完整的标准格式（行程类型）/（舱位代码）（舱位代码）...（舱位代码）/（判断）（折扣数值）
                if (key.indexOf("RT/") < 0 && key.indexOf("OW/") < 0) {
                    // 默认单程
                    key = "OW/" + key;
                }
                // （行程类型）
                String tripType = key.split("/")[0].trim();
                // （舱位代码）
                String cabinList = key.split("/")[1].trim();
                String campareString = "";
                // （判断）（折扣数值）
                if (key.split("/").length == 3) {
                    campareString = key.split("/")[2].trim();
                }
                if (tripType.equals(type) && cabinList.indexOf(cabinCode) >= 0) {
                    if (!campareString.equals("")) {
                        // 与配置文件比较

                        if (compare(selectDiscount, campareString)) {
                            returnVal = entry.getValue();
                            break;
                        }
                    } else {
                        // 无折扣配置项，取默认值

                        returnVal = entry.getValue();
                        break;
                    }
                }
            }

            return returnVal;
        }

        /**
         * 匹配政策-比较舱位折扣
         *
         * @param discount
         *            选择舱位折扣
         * @param campareString
         *            配置比较字符串
         *
         *
         *
         * @return 配置匹配true
         */
        public static boolean compare(double discount, String campareString) {
            boolean retVal = false;
            // 比较符号
            String exp = "";
            // 比较值

            String cv = "";
            double compareDiscount;
            campareString = campareString.trim();
            if (campareString.equals("") || discount <= 0) {
                // 空配置表示全部折扣适用
                return true;
            }
            if (campareString.indexOf("<=") >= 0
                    || campareString.indexOf(">=") >= 0) {
                exp = campareString.substring(0, 2);
                cv = campareString.substring(2);
            } else if (campareString.indexOf("<") >= 0
                    || campareString.indexOf("=") >= 0
                    || campareString.indexOf(">") >= 0) {
                exp = campareString.substring(0, 1);
                cv = campareString.substring(1);
            }
            try {
                compareDiscount = Double.parseDouble(cv);
                if (exp.equals("<=")) {
                    retVal = (discount <= compareDiscount);
                } else if (exp.equals(">=")) {
                    retVal = (discount >= compareDiscount);
                } else if (exp.equals("<")) {
                    retVal = (discount < compareDiscount);
                } else if (exp.equals("=")) {
                    retVal = (discount == compareDiscount);
                } else if (exp.equals(">")) {
                    retVal = (discount > compareDiscount);
                } else {
                    retVal = false;
                }
            } catch (Exception ex) {
                retVal = false;
            }
            return retVal;
        }
    }
}
